#include "adminwindow.h"
#include "../../ui/ui_adminwindow.h"
#include "loginwindow.h"
#include "file_transfer_client.h"
#include <QMessageBox>
#include "database.h"
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QFileDialog>
#include <QInputDialog>

#include "adduserdialog.h"


AdminWindow::AdminWindow(const QString &username, QWidget *parent)
    : QMainWindow(parent), ui(new Ui::AdminWindow), currentUser(username) {
    ui->setupUi(this);
    setWindowTitle("管理员控制台 - " + username);
}

AdminWindow::~AdminWindow() {
    delete ui;
}

void AdminWindow::on_listAllFilesButton_clicked() {
    QList<QMap<QString, QString>> files = Database::listAllFiles();

    if (files.isEmpty()) {
        QMessageBox::information(this, "结果", "暂无上传记录。");
        return;
    }

    QTableWidget *table = new QTableWidget(this);
    table->setColumnCount(4);
    table->setRowCount(files.size());
    table->setHorizontalHeaderLabels(QStringList() << "用户名" << "文件名" << "上传时间" << "大小");

    for (int i = 0; i < files.size(); ++i) {
        const auto &row = files[i];
        table->setItem(i, 0, new QTableWidgetItem(row["username"]));
        table->setItem(i, 1, new QTableWidgetItem(row["filename"]));
        table->setItem(i, 2, new QTableWidgetItem(row["upload_time"]));
        table->setItem(i, 3, new QTableWidgetItem(row["size"]));
    }

    table->resizeColumnsToContents();
    table->setWindowTitle("所有上传文件");
    table->resize(600, 400);
    table->show();
}


void AdminWindow::on_addUserButton_clicked() {
    AddUserDialog dlg(this);
    dlg.exec();
}

void AdminWindow::on_deleteFileButton_clicked() {
    QMessageBox::information(this, "提示", "此功能待实现：删除文件");
}

void AdminWindow::on_viewLogButton_clicked() {
    FileTransferClient client("127.0.0.1", 8888);
    QString error, content = client.getLogContent(currentUser, error);

    if (!error.isEmpty()) {
        QMessageBox::warning(this, "查看失败", error);
        return;
    }

    QMessageBox::information(this, "系统日志", content);
}

void AdminWindow::on_logoutButton_clicked() {
    LoginWindow *login = new LoginWindow();
    login->show();
    this->close();
}
